<template>
  <div class="slaughter-info">
    <!-- 屠宰信息 -->
    <div class="info-section">
      <div class="info-header">
        <h4 class="info-title">屠宰信息 <span class="info-count">设置 {{ Object.keys(localData).length }}</span></h4>
        <div class="info-actions">
          <el-button v-if="!editing" type="primary" size="small" @click="onEdit">
            <el-icon><Setting /></el-icon>
            设置
          </el-button>
          <template v-else>
            <el-button type="success" size="small" @click="onSave">
              <el-icon><View /></el-icon>
              保存
            </el-button>
            <el-button type="info" size="small" @click="onCancel">
              <el-icon><Close /></el-icon>
              取消
            </el-button>
          </template>
        </div>
      </div>
      <div class="info-grid">
        <div class="info-item">
          <label>批次:</label>
          <el-input 
            v-if="editing" 
            v-model="localData.batch" 
            size="small" 
            placeholder="请输入批次号"
            maxlength="20"
          />
          <span v-else>{{ localData.batch || '暂无数据' }}</span>
        </div>
        <div class="info-item">
          <label>到厂均重:</label>
          <el-input 
            v-if="editing" 
            v-model="localData.averageWeight" 
            size="small" 
            type="number" 
            placeholder="请输入到厂均重"
            min="0"
            max="999999"
          >
            <template #append>公斤</template>
          </el-input>
          <span v-else>{{ localData.averageWeight ? `${localData.averageWeight}公斤` : '暂无数据' }}</span>
        </div>
        <div class="info-item">
          <label>到厂时间:</label>
          <el-date-picker 
            v-if="editing" 
            v-model="localData.arrivalTime" 
            size="small" 
            type="datetime" 
            placeholder="请选择到厂时间"
            format="YYYY年MM月DD日 HH:mm:ss"
            value-format="YYYY年MM月DD日 HH:mm:ss"
          />
          <span v-else>{{ localData.arrivalTime || '暂无数据' }}</span>
        </div>
        <div class="info-item">
          <label>屠宰时间:</label>
          <el-date-picker 
            v-if="editing" 
            v-model="localData.slaughterTime" 
            size="small" 
            type="datetime" 
            placeholder="请选择屠宰时间"
            format="YYYY年MM月DD日 HH:mm:ss"
            value-format="YYYY年MM月DD日 HH:mm:ss"
          />
          <span v-else>{{ localData.slaughterTime || '暂无数据' }}</span>
        </div>
      </div>
    </div>

    <!-- 相关资质 -->
    <div class="info-section">
      <h4 class="info-title">相关资质</h4>
      <div class="certificate-gallery">
        <div v-for="cert in quarantineCertificates" :key="cert.id" class="certificate-item">
          <el-image :src="cert.url" fit="cover" class="certificate-img">
            <template #error>
              <div class="image-placeholder">
                <el-icon><Document /></el-icon>
              </div>
            </template>
          </el-image>
          <div class="certificate-label">{{ cert.label }}</div>
          <el-button 
            type="danger" 
            size="small" 
            circle 
            class="remove-btn"
            @click="removeCertificate(cert)"
          >
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        <div class="add-certificate" v-if="quarantineCertificates.length < 9">
          <el-upload
            action="#"
            :show-file-list="false"
            :before-upload="handleCertificateUpload"
            accept="image/*"
            :disabled="quarantineCertificates.length >= 9"
          >
            <div class="upload-area">
              <el-icon><Plus /></el-icon>
              <div>新增</div>
              <div class="upload-tip">最多9张照片</div>
            </div>
          </el-upload>
        </div>
      </div>
    </div>

    <!-- 企业信息 -->
    <div class="info-section">
      <div class="info-header">
        <h4 class="info-title">企业信息 <span class="info-count">设置 {{ Object.keys(enterpriseData).length }}</span></h4>
        <div class="info-actions">
          <el-button v-if="!editingEnterprise" type="primary" size="small" @click="editEnterprise">
            <el-icon><Setting /></el-icon>
            设置
          </el-button>
          <template v-else>
            <el-button type="success" size="small" @click="saveEnterprise">
              <el-icon><View /></el-icon>
              保存
            </el-button>
            <el-button type="info" size="small" @click="cancelEnterprise">
              <el-icon><Close /></el-icon>
              取消
            </el-button>
          </template>
        </div>
      </div>
      <div class="info-grid">
        <div class="info-item">
          <label>公司名称:</label>
          <el-input 
            v-if="editingEnterprise" 
            v-model="enterpriseData.companyName" 
            size="small" 
            placeholder="请输入公司名称"
            maxlength="100"
          />
          <span v-else>{{ enterpriseData.companyName || '暂无数据' }}</span>
        </div>
        <div class="info-item">
          <label>成立时间:</label>
          <el-date-picker 
            v-if="editingEnterprise" 
            v-model="enterpriseData.establishmentDate" 
            size="small" 
            type="date" 
            placeholder="请选择成立时间"
            format="YYYY年MM月DD日"
            value-format="YYYY年MM月DD日"
          />
          <span v-else>{{ enterpriseData.establishmentDate || '暂无数据' }}</span>
        </div>
        <div class="info-item full-width">
          <label>公司地址:</label>
          <el-input 
            v-if="editingEnterprise" 
            v-model="enterpriseData.address" 
            size="small" 
            placeholder="请输入公司地址"
            maxlength="200"
          />
          <span v-else>{{ enterpriseData.address || '暂无数据' }}</span>
        </div>
        <div class="info-item full-width">
          <label>公司简介:</label>
          <el-input 
            v-if="editingEnterprise" 
            v-model="enterpriseData.profile" 
            type="textarea" 
            :rows="4"
            size="small" 
            placeholder="请输入公司简介"
            maxlength="500"
            show-word-limit
          />
          <span v-else class="profile-text">{{ enterpriseData.profile || '暂无数据' }}</span>
        </div>
      </div>
    </div>

    <!-- 企业照片 -->
    <div class="info-section">
      <h4 class="info-title">企业照片</h4>
      <div class="photo-gallery">
        <div v-for="photo in enterprisePhotos" :key="photo.id" class="photo-item">
          <el-image :src="photo.url" fit="cover" class="photo-img">
            <template #error>
              <div class="image-placeholder">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
          <el-button 
            type="danger" 
            size="small" 
            circle 
            class="remove-btn"
            @click="removePhoto(photo)"
          >
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        <div class="add-photo" v-if="enterprisePhotos.length < 9">
          <el-upload
            action="#"
            :show-file-list="false"
            :before-upload="handlePhotoUpload"
            accept="image/*"
            :disabled="enterprisePhotos.length >= 9"
          >
            <div class="upload-area">
              <el-icon><Plus /></el-icon>
              <div>新增</div>
              <div class="upload-tip">最多9张照片</div>
            </div>
          </el-upload>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Setting,
  View,
  Close,
  Plus,
  Document,
  Picture
} from '@element-plus/icons-vue'

const props = defineProps<{ 
  data: any,
  quarantineData: any[],
  quarantineCertificates: any[],
  enterpriseData: any,
  enterprisePhotos: any[]
}>()

const emit = defineEmits(['save', 'cancel', 'updateQuarantine', 'updateCertificates', 'updateEnterprise', 'updatePhotos'])

const editing = ref(false)
const editingEnterprise = ref(false)

const localData = ref({ ...props.data })
const quarantineData = ref([...props.quarantineData])
const quarantineCertificates = ref([...props.quarantineCertificates])
const enterpriseData = ref({ ...props.enterpriseData })
const enterprisePhotos = ref([...props.enterprisePhotos])

watch(() => props.data, (val) => {
  localData.value = { ...val }
})

watch(() => props.quarantineData, (val) => {
  quarantineData.value = [...val]
})

watch(() => props.quarantineCertificates, (val) => {
  quarantineCertificates.value = [...val]
})

watch(() => props.enterpriseData, (val) => {
  enterpriseData.value = { ...val }
})

watch(() => props.enterprisePhotos, (val) => {
  enterprisePhotos.value = [...val]
})

// 屠宰信息操作
const onEdit = () => { 
  editing.value = true 
  ElMessage.info('进入编辑模式')
}

const onSave = () => { 
  // 验证必填字段
  if (!localData.value.batch || !localData.value.averageWeight || 
      !localData.value.arrivalTime || !localData.value.slaughterTime) {
    ElMessage.warning('请填写所有必填字段')
    return
  }
  
  emit('save', localData.value)
  editing.value = false 
  ElMessage.success('屠宰信息保存成功')
}

const onCancel = () => { 
  emit('cancel')
  editing.value = false 
  ElMessage.info('已取消编辑')
}

// 企业信息操作
const editEnterprise = () => {
  editingEnterprise.value = true
  ElMessage.info('进入编辑模式')
}

const saveEnterprise = async () => {
  try {
    // 验证必填字段
    if (!enterpriseData.value.companyName || !enterpriseData.value.establishmentDate || 
        !enterpriseData.value.address || !enterpriseData.value.profile) {
      ElMessage.warning('请填写所有必填字段')
      return
    }
    
    emit('updateEnterprise', enterpriseData.value)
    editingEnterprise.value = false
    ElMessage.success('企业信息保存成功')
  } catch (error) {
    ElMessage.error('保存失败，请重试')
  }
}

const cancelEnterprise = () => {
  editingEnterprise.value = false
  ElMessage.info('已取消编辑')
}

// 图片上传操作
const handleCertificateUpload = (file: File) => {
  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  
  // 验证文件大小（5MB）
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过5MB')
    return false
  }
  
  // 验证数量限制
  if (quarantineCertificates.value.length >= 9) {
    ElMessage.warning('最多只能上传9张相关资质')
    return false
  }
  
  // 弹出选择标签的对话框
  ElMessageBox.prompt('请为这张图片添加标签（如：宰前检疫、宰后质检等）', '添加标签', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^[\u4e00-\u9fa5a-zA-Z0-9]+$/,
    inputErrorMessage: '标签只能包含中文、字母和数字'
  }).then(({ value }) => {
    const newCert = {
      id: Date.now(),
      url: URL.createObjectURL(file),
      name: file.name,
      label: value
    }
    quarantineCertificates.value.push(newCert)
    emit('updateCertificates', quarantineCertificates.value)
    ElMessage.success('相关资质上传成功')
  }).catch(() => {
    ElMessage.info('已取消上传')
  })
  
  return false
}

const removeCertificate = (cert: any) => {
  const index = quarantineCertificates.value.findIndex(item => item.id === cert.id)
  if (index > -1) {
    quarantineCertificates.value.splice(index, 1)
    emit('updateCertificates', quarantineCertificates.value)
    ElMessage.success('相关资质删除成功')
  }
}

const handlePhotoUpload = (file: File) => {
  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  
  // 验证文件大小（5MB）
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过5MB')
    return false
  }
  
  // 验证数量限制
  if (enterprisePhotos.value.length >= 9) {
    ElMessage.warning('最多只能上传9张企业照片')
    return false
  }
  
  const newPhoto = {
    id: Date.now(),
    url: URL.createObjectURL(file),
    name: file.name
  }
  enterprisePhotos.value.push(newPhoto)
  emit('updatePhotos', enterprisePhotos.value)
  ElMessage.success('企业照片上传成功')
  return false
}

const removePhoto = (photo: any) => {
  const index = enterprisePhotos.value.findIndex(item => item.id === photo.id)
  if (index > -1) {
    enterprisePhotos.value.splice(index, 1)
    emit('updatePhotos', enterprisePhotos.value)
    ElMessage.success('企业照片删除成功')
  }
}
</script>

<script lang="ts">
export default {
  name: 'SlaughterInfo'
}
</script>

<style scoped>
.slaughter-info {
  padding: 20px;
  overflow-y: auto;
}

.info-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fff;
}

.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.info-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.info-count {
  font-size: 12px;
  color: #909399;
  font-weight: normal;
}

.info-actions {
  display: flex;
  gap: 8px;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.info-item.full-width {
  grid-column: 1 / -1;
}

.info-item label {
  min-width: 80px;
  font-weight: 500;
  color: #606266;
  margin-top: 4px;
}

.profile-text {
  white-space: pre-wrap;
  line-height: 1.5;
  color: #606266;
}

.certificate-gallery,
.photo-gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.certificate-item,
.photo-item {
  position: relative;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
}

.certificate-img,
.photo-img {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.certificate-label {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 4px 8px;
  font-size: 12px;
  text-align: center;
}

.remove-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 10;
  background: rgba(0, 0, 0, 0.5);
  border: none;
  color: white;
}

.remove-btn:hover {
  background: rgba(245, 108, 108, 0.8);
}

.add-certificate,
.add-photo {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 150px;
  cursor: pointer;
  transition: border-color 0.3s;
}

.add-certificate:hover,
.add-photo:hover {
  border-color: #409eff;
}

.upload-area {
  text-align: center;
  color: #909399;
}

.upload-area .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.upload-tip {
  font-size: 12px;
  color: #c0c4cc;
  margin-top: 4px;
}

.image-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.image-placeholder .el-icon {
  font-size: 32px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .info-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .info-actions {
    justify-content: center;
  }
  
  .certificate-gallery,
  .photo-gallery {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
}
</style> 